from plyny.workstreams import Manager


if __name__ == '__main__':
    import sys
    parser = sys.argv[1]
    import cPickle
    parser = cPickle.load(open(parser))
    args = parser.process_command_line(sys.argv[2:])

    for key, arg in args.iteritems():
        locals()[key] = arg

    open_manager = Manager(open_manager)
    inputstream = open_manager.stream.open(args['inputstream'])

    if outof > 1:
        inputstream = inputstream.get_group(args['index'], args['outof'])

    modulecomponents = runner.split('.')
    m = __import__('.'.join(modulecomponents[:-1]))
    mod = m.__dict__[modulecomponents[-2]]

    import inspect
    func = mod.__dict__[modulecomponents[-1]]
    actual_function_args = inspect.getargspec(func).args
    called_values = {}
    order = {}
    for i, arg in enumerate(actual_function_args):
        if arg == 'manager':
            val = args['create_manager']
        else:
            val = args[arg]
        called_values[arg] = val
        order[arg] = i

    create_manager = Manager(create_manager, process=args['outputname'])
    if args['outof'] > 1:
        create_manager = create_manager.substream(str(index))
    
    called_values['inputstream'] = inputstream
    called_values['manager'] = create_manager
    args = []
    for key, i in sorted(order.iteritems(), key=lambda x: x[1]):
        args.append(called_values[key])

    func(*args)
